package com.lsl.rdf.aop;

import com.lsl.rdf.basics.EnumDescInjectUtil;
import com.lsl.rdf.callback.InjectEnumDescAopCallback;
import com.lsl.rdf.result.page.PageResult;
import com.lsl.rdf.result.success.SuccessResult;
import com.lsl.rdf.tuple.Tuple;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Objects;

/**
 * Created by lsl on 2021/4/26.
 */
@Aspect
@SuppressWarnings({"unchecked", "rawtypes"})
public class InjectEnumDescAop {

    @Autowired(required = false)
    private InjectEnumDescAopCallback injectEnumDescAopCallback;

    @Pointcut("@annotation(com.lsl.rdf.annotation.InjectEnumResult)")
    public void pointCut() {
    }

    @AfterReturning(returning = "result", pointcut = "pointCut()")
    public Object afterReturn(Object result) {
        if (result instanceof SuccessResult) {
            Object data = ((SuccessResult) result).getData();
            if (data instanceof List) {
                EnumDescInjectUtil.invadeFieldsSetDesc((List<Object>) data);
            } else if (data instanceof PageResult) {
                List list = ((PageResult) data).getList();
                EnumDescInjectUtil.invadeFieldsSetDesc(list);
            } else if (data instanceof Tuple) {
                Object first = ((Tuple) data).getFirst();
                if (first instanceof List) {
                    EnumDescInjectUtil.invadeFieldsSetDesc((List<Object>) first);
                } else {
                    EnumDescInjectUtil.invadeFieldSetDesc(first);
                }
            } else {
                EnumDescInjectUtil.invadeFieldSetDesc(data);
            }
        }
        // 执行回调方法
        if (Objects.nonNull(injectEnumDescAopCallback)) {
            return injectEnumDescAopCallback.injectEnumDescCallback(result);
        }

        return result;
    }
}
